package com.example.blog.event.describe;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.blog.domain.*;
import com.example.blog.event.publisher.UserInformationApplicationEvent;
import com.example.blog.event.publisher.WritingApplicationEvent;
import com.example.blog.service.impl.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Async
public class UserInfoListen implements ApplicationListener<UserInformationApplicationEvent> {
    private final WritingsServiceImpl writingsService;
    private final CommentsServiceImpl commentsService;
    private final UserServiceImpl userService;
    private final UserRoleServiceImpl userRoleService;

    @Autowired
    private UserInfoListen(WritingsServiceImpl writingsService,
                           UserServiceImpl userService,
                           CommentsServiceImpl commentsService,
                           UserRoleServiceImpl userRoleService
    ) {
        this.writingsService = writingsService;
        this.userService = userService;
        this.commentsService = commentsService;
        this.userRoleService = userRoleService;
    }


    public void onApplicationEvent(UserInformationApplicationEvent event) {
        UserInformation users = (UserInformation) event.getSource();
        LambdaQueryWrapper<Writings> sw = new LambdaQueryWrapper<>();
        QueryWrapper<Comments> wrapper = new QueryWrapper<>();
        List<Writings> writings = writingsService.list(sw.eq(Writings::getUid, users.getUid()).select(Writings::getWid, Writings::getImg));
        if (writings.size() > 0) {
            List<String> imgList = (writings.stream().map(Writings::getImg).collect(Collectors.toList())).stream().distinct().collect(Collectors.toList());
            List<String> wid = writings.stream().map(Writings::getWid).collect(Collectors.toList());
            commentsService.remove(wrapper.in("wid", wid)); //删除文章评论
            imgList.add(users.getAvatar());
            writingsService.delImg(Arrays.stream(wid.toArray(new String[0])).toArray(String[]::new)); //删除文章图片
        }
        writingsService.remove(new LambdaQueryWrapper<Writings>().eq(Writings::getUid, users.getUid())); //删除文章信息
        userService.remove(new LambdaQueryWrapper<Users>().eq(Users::getUid, users.getUid())); //删除账号信息
        userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUid, users.getUid()));
    }
}
